import { Injectable } from '@nestjs/common';
import { Scheduled_Create_Dto, Scheduled_Update_Dto } from './assets/scheduled.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Scheduled } from './assets/scheduled.entity';
import { Repository } from 'typeorm';
import { util_Db_Add } from '@/common/util/db';
import {
  Constant_Enum_Enum_Scheduled_Status,
  Constant_Enum_Enum_Scheduled_Type,
} from '@/common/constants/enum';
import { Class_HttpException_Base } from '@/common/classes/httpException';

@Injectable()
export class Scheduled_Service {
  constructor(
    @InjectRepository(Scheduled)
    private scheduled_Repository: Repository<Scheduled>,
  ) {}

  async scheduled_Create(body: Scheduled_Create_Dto) {
    return await util_Db_Add<Scheduled>({
      createDto: body,
      repository: this.scheduled_Repository,
      returnObj: true,
    });
  }

  async scheduled_FindOneById(id: number) {
    return await this.scheduled_Repository
      .createQueryBuilder('scheduled')
      .andWhere(`scheduled.id = :id`, { id: id })
      .getOne();
  }

  async scheduled_FindOneByName(name: string) {
    return await this.scheduled_Repository
      .createQueryBuilder('scheduled')
      .andWhere(`scheduled.scheduledName = :scheduledName`, {
        scheduledName: name,
      })
      .getOne();
  }

  async scheduled_Update(body: Scheduled_Update_Dto) {
    const scheduled = await this.scheduled_FindOneById(body.id);
    if (!scheduled) throw new Class_HttpException_Base('不存在该记录');
    const newRole = this.scheduled_Repository.merge(scheduled, body);
    await this.scheduled_Repository.save(newRole);
    return '编辑成功';
  }

  async scheduled_FindAllByType() {
    return await this.scheduled_Repository
      .createQueryBuilder('scheduled')
      .andWhere(`scheduled.scheduleddType = :scheduleddType`, {
        scheduleddType: Constant_Enum_Enum_Scheduled_Type.Scheduled_Type_OrderPay,
      })
      .andWhere(`scheduled.status = :status`, {
        status: Constant_Enum_Enum_Scheduled_Status.SCHEDULED_STATUS_PENDING,
      })
      .getMany();
  }
}
